package net.roobook.common.configure;

import feign.RequestInterceptor;
import net.roobook.common.entity.RoobookConstant;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.util.Base64Utils;

/**
 * @Author Roobook
 * @description 配置类里注册一个Feign请求拦截器
 * @date 2022/4/8
 */
public class RoobookOAuth2FeignConfigure {
    @Bean
    public RequestInterceptor oauth2FeignRequestInterceptor() {
        return requestTemplate -> {
            // Feign调用里添加Zuul Token
            String zuulToken = new String(Base64Utils.encode(RoobookConstant.ZUUL_TOKEN_VALUE.getBytes()));
            requestTemplate.header(RoobookConstant.ZUUL_TOKEN_HEADER, zuulToken);

            // 通过SecurityContextHolder从请求上下文中获取了OAuth2AuthenticationDetails类型对象
            Object details = SecurityContextHolder.getContext().getAuthentication().getDetails();
            if (details instanceof OAuth2AuthenticationDetails) {
                // 通过OAuth2AuthenticationDetails对象获取到了请求令牌
                String authorizationToken = ((OAuth2AuthenticationDetails) details).getTokenValue();
                // 在请求模板对象requestTemplate的头部手动将令牌添加上去
                requestTemplate.header(HttpHeaders.AUTHORIZATION, "bearer " + authorizationToken);
            }
        };
    }
}
